package codeRandomThoughts.Test236二叉树的最近公共祖先;

import codeRandomThoughts.utils.TreeNode;

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        return postorderHandle(root,p,q);
    }

    public TreeNode postorderHandle(TreeNode root, TreeNode p, TreeNode q) {
        //递归的终止条件
        if (root == null || (root == p || root == q)) {
            return root;
        }

        TreeNode left = postorderHandle(root.left, p, q);
        TreeNode right = postorderHandle(root.right, p, q);

        //如果左右子树非空,说明就是最近公共祖先
        if (left != null && right != null) {
            return root;
        } else if (left == null && right != null) {
            return right;
        } else if (left != null && right == null) {
            return left;
        } else {
            return null;
        }
    }
}
